import isomorphicFetch from 'isomorphic-fetch'
import {hashHistory} from 'react-router'
import {SEND_SMS, REQUEST_SEND_SMS, COUNT_DOWN_SECOND} from '../../config/ActionType'
import {fetch, API_SEND_SMS, API_BIND_MOBILE} from '../../config/Api'
import {showMessage, setLoginToken} from '../../global/actions/'

export const sendingSms = status => ({
  type: SEND_SMS,
  payload: {sending: status}
})

export const countDownSec = sec => ({
  type: COUNT_DOWN_SECOND,
  payload: {sec}
})

export function fetchSendSMS(params) {
  let headers = new Headers(),
    body = new FormData()

  headers.append('login-token', sessionStorage.getItem('token'))

  for (let i in params) {
    body.append(i, params[i])
  }

  return (dispatch, getState) => {
    if (getState().login.sending) {
      return
    }

    dispatch(sendingSms(true))

    return isomorphicFetch(API_SEND_SMS.url, Object.assign({}, API_SEND_SMS.config, {headers, body}))
      .then(res => res.json())
      .then(json => {
        if (!json.success) {
          dispatch(showMessage(json.message))
        } else {
          return dispatch(countDownSec(60))
        }
      })
  }
}

export function fetchBindMobile(params, url) {
  return (dispatch, getState) => fetch(API_BIND_MOBILE, params)(dispatch, getState).then(json => {
    if (json.success) {
      let token = sessionStorage.getItem('token')

      dispatch(setLoginToken(token, true))
      if (url) {
        hashHistory.replace(url)
      } else {
        hashHistory.replace('/home')
      }
    } else {
      dispatch(showMessage(json.message))
    }
  })
}

export const actions = {
  fetchSendSMS,
  sendingSms,
  fetchBindMobile,
  countDownSec
}

export const ACTION_HANDLERS = {
  [SEND_SMS]: (state, action) => ({...state, sending: action.payload.sending}),
  [COUNT_DOWN_SECOND]: (state, action) => ({...state, sec: action.payload.sec})
}

const initialState = {
  sending: false,
  sec: 60
}

export default function(state = initialState, action) {
  const handler = ACTION_HANDLERS[action.type]

  return handler ? handler(state, action) : state
}
